<template>
  <div class="update-photo">
    <img class="img" :src="img" alt="" ref="img">
    <div class="toolbar">
      <div class="cancle" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/users.js'
export default {
  name: 'UpdatePhoto',
  data() {
    return {
      cropper: null
    }
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  methods: {
    onConfirm() {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updatePhoto(blob)
      })
    },
    async updatePhoto(blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        // 这种写法是错误的
        // 如果接口要求是Content-Type是application/json
        // 则传递的是普通的JavaScript对象
        // updateUserPhoto({
        //   photo: blob
        // })
        // 如果接口要求传递的是Content-Type是multipart/form-data
        // 则需要传递formData对象
        const formData = new FormData()
        formData.append('photo', blob)
        // 调用接口
        const { data } = await updateUserPhoto(formData)
        // console.log(data)
        // 关闭弹出层
        this.$emit('close')
        // 更新视图
        this.$emit('update-photo', data.data.photo)
        this.$toast.success('更新成功')
      } catch (err) {
        this.$toast.fail('更新失败')
      }
    }
  },
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    // console.log(cropper)
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  height: 100%;
  background-color: #000;
  .img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }
  .cancle,
  .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
